

package com.asisto.model

class PersonaController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ personaInstanceList: Persona.list( params ), personaInstanceTotal: Persona.count() ]
    }

    def show = {
        def personaInstance = Persona.get( params.id )

        if(!personaInstance) {
            flash.message = "Persona not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ personaInstance : personaInstance ] }
    }

    def delete = {
        def personaInstance = Persona.get( params.id )
        if(personaInstance) {
            try {
                personaInstance.delete(flush:true)
                flash.message = "Persona ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Persona ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Persona not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def persona = Persona.get( params.id )

        if(!persona) {
            flash.message = "Persona not found with id ${params.id}"
            redirect(action:list)
        }
        else {

            //Crea lista de padres

            def listaPadres = persona.padres.collect{ it.padre }
            return [ personaInstance : persona, listaPadres: listaPadres ]
        }
    }

    def update = {
        def personaInstance = Persona.get( params.id )
        if(personaInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(personaInstance.version > version) {
                    
                    personaInstance.errors.rejectValue("version", "persona.optimistic.locking.failure", "Another user has updated this Persona while you were editing.")
                    render(view:'edit',model:[personaInstance:personaInstance])
                    return
                }
            }
            personaInstance.properties = params
            if(!personaInstance.hasErrors() && personaInstance.save()) {
                flash.message = "Persona ${params.id} updated"
                redirect(action:show,id:personaInstance.id)
            }
            else {
                render(view:'edit',model:[personaInstance:personaInstance])
            }
        }
        else {
            flash.message = "Persona not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def personaInstance = new Persona()
        personaInstance.properties = params
        return ['personaInstance':personaInstance]
    }

    def save = {
        def personaInstance = new Persona(params)
        if(!personaInstance.hasErrors() && personaInstance.save()) {
            flash.message = "Persona ${personaInstance.id} created"
            redirect(action:show,id:personaInstance.id)
        }
        else {
            render(view:'create',model:[personaInstance:personaInstance])
        }
    }

    def nuevoPadre = {

        def listaPadres  = []
        println "params: $params"

        def persona = Persona.get( params.idHijo )

        if(!persona) {
            flash.message = "Persona not found with id ${params.idHijo}"
            redirect(action:list)
        }
        else {

            //Obtiene los padres de los params

            def nuevosPadres = []
            params.each { key, value ->
                if (key =~ /nombre_\d/) {
                    println "$key -> $value"

                    def nombre = value
                    def partes = key.split('_')
                    def indice = partes[1]

                    //Obtiene el apellido correspondiente
                    def apellidos = params."apellidos_$indice"

                    println "Nombre: $nombre, apellidos: $apellidos"

                    Persona padre = new Persona(nombre:nombre,apellidos:apellidos)
                    Padre relacion = new Padre(padre:padre, hijo: persona)

                    padre.addToHijos(relacion)
                    persona.addToPadres(relacion)

                    padre.save(flush:true)

                    
                }


                
            }

            flash.message = 'Padres añadidos.'

            //Crea lista de padres
            listaPadres = persona.padres.collect{ it.padre }
        }

        render(view:'edit', model: [ personaInstance : persona, listaPadres: listaPadres ])
        
    }
}
